package basetest;

import org.junit.Test;
import utils.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;

/**
 * 查询
 */
public class QueryTest {
    @Test
    public void test() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null; // 保存查询结果
        ArrayList<Employee> employees = new ArrayList<>();  // 表对应的对象列表
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from new_table2";  // 查询所有信息
            ps = conn.prepareStatement(sql);  // 语句传进statement中
            rs = ps.executeQuery(); // 获取查询结果
            if (rs != null) {
                while (rs.next()) {
                    employees.add(new Employee(rs.getInt(1), rs.getString(2),
                            rs.getString(3), rs.getString(4), rs.getString(5),
                            rs.getString(6), rs.getDouble(7), rs.getDouble(8),
                            rs.getInt(9), rs.getInt(10), rs.getTimestamp(11)));
                }
            }
            for (Employee employee : employees) {
                System.out.println(employee);
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeSource(conn);
            JDBCUtils.closeSource(ps);
            JDBCUtils.closeSource(rs);
        }
    }

    @Test
    public void test2() {
        String sql = "select * from new_table2;";  // 查询所有信息
        ArrayList<Employee> employees = JDBCUtils.queryFromTable(Employee.class, sql);  // 从数据库中读出数据，并初始化成对象列表
        if (employees != null) {
            System.out.println(employees.size());
            for (Employee employee : employees) {
                System.out.println(employee.toString());
            }
        }
    }


}
